﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIBattle : BaseUI {
    const string BaseText = "生命值：";
    public static int bloods;
    int blood;
    bool isClicked = false;
    Text BloodsText;
    Text countDowntext;
    int countDownNum;
    Vector3 towerPoint;
    GameObject bloodBar;
    GameObject towerBtns;
    GameObject setPanel;


    private void Update()
    {
        UpdateBlood();//血量标签更新
        MoveCamera();//相机位置控制
        ReasultBattle();//结果判断
        TowerPoint();//塔放置点
    }
    IEnumerator CountDown()
    {
        for(int i=0;i<countDownNum;i++)
        {
            countDowntext.text = (countDownNum - i).ToString();
            yield return new WaitForSeconds(1);
        }
        countDowntext.gameObject.SetActive(false);
        
    }

    #region 重载方法
    public override void LoadInit(string level)
    {
        base.LoadInit();
        AudioManage.BgPlay("music_fuben");
        Spawner.mapRoads = MapManage.LoadPath(level);
        Spawner.MapDraw();
        bloods = 6;
        blood = bloods;
        countDownNum = 5;
        Spawner.IsAll = false;
        Spawner.Instance.SpawnMonster(bloodBar,this.transform);
        StopAllCoroutines();
        StartCoroutine(CountDown());
    }
    //重写退出UI
    public override void ExitUI()
    {
        AudioManage.BgPlay("music_login");
        Spawner.MapClear();
        Pools.Instance.UnspawnAll();
        base.ExitUI();

    }

    private void OnDestroy()
    {
        Debug.Log("Destroy uibattle");
    }

    public override void BindCompotent(string imgName, GameObject go)
    {
        switch (imgName)
        {
            case "LiefText":
                BloodsText= go.GetComponent<Text>();
                break;
            case "CountDownText":
                countDowntext = go.GetComponent<Text>();
                go.SetActive(true);
                break;
            case "EnemyBloodBar":
                bloodBar = go;
                go.SetActive(false);
                break;
            case "TowerBtns":
                towerBtns = go;
                go.SetActive(false);
                break;
            case "SetPanel":
                setPanel = go;
                go.SetActive(false);
                break;
            default:
                break;
        }
    }
    public override void OnButtonClick(string btnName)
    {
        switch (btnName)
        {
            case "BtnTower1":
                Spawner.SpawnTowerr("Warrior_example1", towerPoint);
                towerBtns.SetActive(false);
                isClicked = true;
                break;
            case "BtnTower2":
                Spawner.SpawnTowerr("Archer_example2", towerPoint);
                towerBtns.SetActive(false);
                isClicked = true;
                break;
            case "BtnPause":
                Time.timeScale = 0;
                setPanel.SetActive(true);
                break;
            case "BtnResume":
                Time.timeScale = 1;
                setPanel.SetActive(false);
                break;
            case "BtnReplay":
                UIManager.ExitUI(this);
                var t = UIManager.EnterUI<UIBattle>();
                t.LoadInit(GameMain.Instance.currentProgress.ToString());
                break;
            case "BtnSelect":
                UIManager.EnterUI<UISelect>();
                UIManager.ExitUI(this);
                break;
            default:
                break;
        }
    }
    
   
    #endregion
   
    #region 战斗结果
    void ReasultBattle()
    {
        if (bloods == 0)
        {
            UIManager.EnterUI<LoseBattle>();
            UIManager.ExitUI(this);
            return;
        }
        else if (!HasMonster())
        {
            if (GameMain.Instance.currentProgress == Saver.GetProgress())
            {
                Saver.SetProgress((GameMain.Instance.currentProgress+1));
                Debug.Log("GetProgress" + Saver.GetProgress());
            }
            UIManager.EnterUI<WinBattle>();
            UIManager.ExitUI(this);
            return;
        }
    }
    //是否还有怪物
    bool HasMonster()
    {
        if (Spawner.IsAll && Spawner.monsters.Count == 0)
        {
            return false;
        }
        return true;
    }
    //更新血量
    void UpdateBlood()
    {
        if (blood > bloods)
        {
            blood = bloods;
            BloodsText.text = BaseText + blood.ToString();
        }

    }
    #endregion
    #region 相机移动

    float currentPD = -1;
    Vector3 currentPoint = Vector3.zero;
    Vector3 firstMouseK = Vector3.zero;
    Vector3 mousePos = Vector3.zero;
    Vector3 currentMousePos = Vector3.zero;
    void MoveCamera()
    {
        //屏幕缩放移动
        if (Input.touchCount > 0 || Input.GetMouseButton(0))
        {
            if (Input.touchCount > 1)
            {
                Touch touch_1 = Input.touches[0];
                Touch touch_2 = Input.touches[1];
                Camera.main.fieldOfView = Mathf.Clamp(Camera.main.fieldOfView, 10f, 90f);
                if (currentPD == -1)
                {
                    currentPD = Vector2.Distance(touch_1.position, touch_2.position);
                }
                else
                {
                    Camera.main.fieldOfView *= Vector2.Distance(touch_1.position, touch_2.position) / currentPD;
                }
            }
            else
            {
                if (currentPD != -1)
                    currentPD = -1;

                Ray ray;
                if (Input.touchCount == 1)
                {

                    ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).deltaPosition);
                }
                else
                {
                    ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                }

                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                    if (hit.collider.gameObject.layer == 9)
                    {
                        if (currentPoint == Vector3.zero)
                        {
                            mousePos =new Vector3(Input.mousePosition.x * 20 / Screen.width, 0, Input.mousePosition.y * 20 / Screen.height);
                            currentPoint = hit.point;
                            firstMouseK = Input.mousePosition;
                        }
                        else
                        {
                            currentMousePos = new Vector3(Input.mousePosition.x * 20 / Screen.width, 0, Input.mousePosition.y * 20 / Screen.height);
                            Camera.main.transform.localPosition += mousePos - currentMousePos;
                            Camera.main.transform.localPosition =new Vector3(Mathf.Clamp(Camera.main.transform.localPosition.x ,-43,43), Camera.main.transform.localPosition.y, Mathf.Clamp(Camera.main.transform.localPosition.z,-50,35));
                            currentPoint = hit.point;
                            mousePos = currentMousePos;
                        }
                    }
                }

            }
        }
        else
        {
            if (currentPoint != Vector3.zero)
                currentPoint = Vector3.zero;
        }

        {//鼠标操作
            if (Input.GetAxis("Mouse ScrollWheel") < 0)
            {
                Camera.main.fieldOfView = Mathf.Clamp(Camera.main.fieldOfView, 10f, 90f);
                Camera.main.fieldOfView *= 0.9f;
            }
            if (Input.GetAxis("Mouse ScrollWheel") > 0)
            {
                Camera.main.fieldOfView = Mathf.Clamp(Camera.main.fieldOfView, 10f, 90f);
                Camera.main.fieldOfView *= 1.1f;
            }
            if (Input.GetKey(KeyCode.W))
            {
                Vector3 pos = Camera.main.transform.localPosition;
                pos.z += 1;
                Camera.main.transform.localPosition = pos;
            }
            if (Input.GetKey(KeyCode.S))
            {
                Vector3 pos = Camera.main.transform.localPosition;
                pos.z -= 1;
                Camera.main.transform.localPosition = pos;
            }
            if (Input.GetKey(KeyCode.D))
            {
                Vector3 pos = Camera.main.transform.localPosition;
                pos.x += 1;
                Camera.main.transform.localPosition = pos;
            }
            if (Input.GetKey(KeyCode.A))
            {
                Vector3 pos = Camera.main.transform.localPosition;
                pos.x -= 1;
                Camera.main.transform.localPosition = pos;
            }
        }//鼠标和键盘操作移动相机
    }
    #endregion
    #region 炮塔基地选址
    void TowerPoint()
    {
        if (Input.GetMouseButtonUp(0))// && firstMouseK != Vector3.zero
        {
            if (towerBtns.activeSelf && !EventSystem.current.IsPointerOverGameObject())
            {
                towerBtns.SetActive(false);
            }
            else if (!towerBtns.activeSelf && !isClicked)
            {
                RaycastHit hit;
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out hit))
                {
                    Vector3 hitPosition = hit.point;
                    towerPoint.x = Mathf.RoundToInt(hitPosition.x);
                    towerPoint.z = Mathf.RoundToInt(hitPosition.z);
                    if (!Spawner.IsTower(towerPoint) && !Spawner.IsMap(towerPoint) && Vector3.Distance(firstMouseK, Input.mousePosition) < 0.01)// 
                    {
                        towerBtns.transform.localPosition = new Vector2((Input.mousePosition.x - Screen.width / 2) * 800f / Screen.width, (Input.mousePosition.y - Screen.height / 2) * 600f / Screen.height);
                        towerBtns.gameObject.SetActive(true);
                    }
                }
            }
            isClicked = false;

        }
    }
    #endregion
}
